package br.ufmg.vod.wbr.algorithims.cluster;

import java.util.Arrays;

import javolution.util.FastSet;
import br.ufmg.vod.wbr.api.Graph;

public class ClusteringCoefficient implements Runnable {

	private final Graph g;
	public double[] res;

	public ClusteringCoefficient(Graph g) {
		this.g = g;
		this.res = new double[g.getNumVertex()];
	}

	@Override
	public void run() {
		int[][] gMatrix = g.getAllEdges();
		for (int vertex = 0; vertex < gMatrix.length; vertex++) {
			
			int[] edgesVertex = gMatrix[vertex];
			
			if (edgesVertex.length < 2) {
				res[vertex] = 0;				
			} else {
				double sum = 0;
				
				//E tirar este set
				FastSet<Integer> considered = new FastSet<Integer>();
				for(int edge = 0; edge < edgesVertex.length; edge++) {
					
					int otherV = gMatrix[vertex][edge];
					int[] edgesOther = gMatrix[otherV];
					
					for (int k = 0; k < edgesOther.length; k++) {
						int key = edgesOther[k];
						if (!considered.contains(key)) {
							int binarySearch = Arrays.binarySearch(edgesVertex, key);
							if (binarySearch > 0) {
								sum++;
							}
						}
						
					}
					considered.add(otherV);
				}
				
				//Tem que tirar isto para não direcionado!!!!
				double d = (edgesVertex.length * (edgesVertex.length - 1)) / 2.0;
				res[vertex] = sum / d;
			}
		}
	}
}